from django.shortcuts import render,redirect
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from django import http
from django.contrib.auth import login
# Django的配置模块，使用哪个配置文件启动，那么settings中就有哪个配置文件的数据
import logging

from meiduo_mall_two.utils.response_code import RETCODE
from django.views import View
from apps.oauth.models import OAuthQQUser

# Create your views here.

# 日志记录
logger = logging.getLogger("django")


#########获取QQ登录扫码页面############
class QQAuthURLView(View):
    """获取QQ登录扫码页面"""

    def get(self, request):
        """提供QQ登录扫码页面链接"""
        # 获取next
        next = request.GET.get('next', '/')
        # 初始化SDK的对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=next)
        # SDK对象调用方法
        login_url = oauth.get_qq_url()
        # 返回QQ登录扫码页面链接
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'login_url': login_url})



########用户扫码登录的回调处理###############
class QQAuthUserView(View):
    """用户扫码登录的回调处理
    实现OAuth2.0认证获取到openid
    """
    def get(self,request):

        # 接收Authorization Code
        code = request.GET.get("code")
        if not code:
            return http.HttpResponseForbidden("缺少code")

        # 初始化SDK的对象: 获取 taken时,state不需要在传入了
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)

        try: # 由于是网络操作,有延迟,需要try
            # 通过Authorization Code获取Access Token
            access_token = oauth.get_access_token(code)
            # 通过Access Token获取openid
            openid = oauth.get_open_id(access_token)
        except Exception as e:
            # logging.info(e) # 只在开发环境下才会输出
            logging.error(e) # 项目部署上线后，最低的等级是error
            return http.HttpResponseServerError("OAuth2.0认证失败")

        # 使用openid查询该QQ用户是否绑定过美多商城用户
        try:
            oauth_model = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            # 如果openid没绑定美多商城用户，进入到绑定用户的页面，创建用户并绑定到openid
            return render(request,"oauth_callback.html")
        else:
            # 如果openid已绑定美多商城用户，直接登入到美多商城系统
            # 实现状态保持
            # login(request, '认证后的用户：跟openid关联的用户即可(外键)
            login(request,oauth_model.user)

            # 重定向state==next
            next = request.GET.get("state")
            response = redirect(next)

            # QQ登陆后的用户写入到cookie
            response.set_cookie('username', oauth_model.user.username, max_age=3600*24*7)

            # 响应结果
            return response




